package com.gitee.maojian.linkedlist;

import java.util.Stack;

/**
 * BM1 反转链表
 */
public class Q_BM01 {

    /**
     * 利用栈实现链表反转
     * 时间复杂度：f = 2n -> O(n)
     * 空间复杂度：O（n）
     * @param head
     * @return
     */
    public ListNode reverseList01(ListNode head) {
        if (head == null) return null;
        Stack<ListNode> stack = new Stack<>();
        ListNode pre = head;
        while (pre != null) {
            stack.push(pre);
            pre = pre.next;
        }
        head = stack.pop();
        pre = head;
        while (!stack.isEmpty()) {
            pre.next = stack.pop();
            pre = pre.next;
        }
        pre.next = null;
        return head;
    }

    /**
     * 当前节点从原链表摘下作为新链表的头结点
     * @param head
     * @return
     */
    public ListNode reverseList(ListNode head) {
        ListNode newNode = null;
        while (head != null) {
            ListNode temp = head.next;
            head.next = newNode;
            newNode = head;
            head = temp;
        }
        return newNode;
    }


}